﻿using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using MessageRouter.Configuration;

namespace MessageRouter.Ftp
{
    public sealed class FtpMessageWriter : MessageWriter
    {
        public FtpMessageWriter(WriterConfigurationElement config)
            : base(config)
        {
        }

        public override void OnNext(RoutedMessage message)
        {
            try
            {
                Uri path = null;
                string fileName = string.Format("{0}.xml", message.MessageId.ToString());
                if (Uri.TryCreate(base.Address, fileName, out path))
                {
                    byte[] data = UTF8Encoding.Default.GetBytes(message.MessageBody.ToString());

                    FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(path);
                    request.Method = WebRequestMethods.Ftp.UploadFile;
                    using (Stream requestStream = request.GetRequestStream())
                    {
                        requestStream.Write(data, 0, data.Length);
                        requestStream.Flush();
                    }
                    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { }
                }
                else
                {
                    throw new InvalidOperationException("can't build an correct Uri");
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("FtpMessageWriter failed with error: {0}", ex.Message);
                throw;
            }
        }
    }
}
